package com.senney.classloader;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author jie.zhang
 * @since 2023/1/16 14:43
 */
public class MyClassLoader extends ClassLoader {

    public static void main(String[] args) throws Exception {
        MyClassLoader myClassLoader = new MyClassLoader();
        Class<?> hello = myClassLoader.loadClass("Hello");
        Object o = hello.newInstance();
        Method method = hello.getDeclaredMethod("sayHello");
        method.invoke(o);
    }

    @Override
    protected Class<?> findClass(String name) {
        Class<?> clazz = this.findLoadedClass(name);
        if (null == clazz) {
            try {
                String classFile = getClassFile(name);
                byte[] bytes = Files.readAllBytes(Paths.get(classFile));
                clazz = defineClass(name, bytes, 0, bytes.length);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return clazz;
    }

    private String getClassFile(String name) {
        StringBuilder sb = new StringBuilder("D:\\test");
        name = name.replace('.', File.separatorChar) + ".class";
        sb.append(File.separator).append(name);
        return sb.toString();

    }
}
